package com.appspot.finajjarane.framework.media.controllers;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.appspot.finajjarane.framework.generic.ApplicationConstants;
import com.appspot.finajjarane.framework.generic.GenericDaoImpl;
import com.appspot.finajjarane.framework.service.IPicasaWeb;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesServiceFactory;

@Controller
@RequestMapping("/media")
public class Media {

	// Setup loggin object
	public static final Logger log = Logger.getLogger(GenericDaoImpl.class.getName());

	@Autowired
	IPicasaWeb iPicasaWeb;

	@RequestMapping("/image/{blobKeyString}")
	public void getArticleImage(
								HttpServletResponse response,
								@PathVariable("blobKeyString") String blobKeyString
								){

		try {
			BlobKey blobKey = new BlobKey(blobKeyString);
			BlobstoreServiceFactory.getBlobstoreService().serve(blobKey, response);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


	// This service resize image and crop it, it's a high performance
	@RequestMapping("/image/thumb/{blobKeyString}/{width}/{crop}")
	public void getArticleImageThumb(
										HttpServletResponse response,
										@PathVariable("blobKeyString") final String blobKeyString,
										@PathVariable("width") final int width,
										@PathVariable("crop") final int cropParam
									) throws IOException{

		boolean crop = false;
		if(cropParam==1){
			crop=true;
		}

		try {
			String urlResizedImage;
			BlobKey blobKey = new BlobKey(blobKeyString);

			urlResizedImage = ImagesServiceFactory.getImagesService().getServingUrl(blobKey, width, crop);
			response.sendRedirect(urlResizedImage);
		} catch (Exception e) {
			response.sendRedirect(iPicasaWeb.getImageUrl(ApplicationConstants.NO_IMAGE_TITLE));
			log.severe(e.getMessage());
		}
	}

	@RequestMapping("/image/picasa/{imageTitle}")
	public void getImageFromPicasaWeb(
										@PathVariable("imageTitle") final String imageTitle,
										HttpServletResponse response
										){
		try {
			response.sendRedirect(iPicasaWeb.getImageUrl(imageTitle));
		} catch (IOException e) {
			log.severe("Error in /media/image/picasa/" + imageTitle + ": \n" + e.getMessage());
		}

	}

}
